<?php


namespace Modules\Manager\Helpers;


use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

trait UserData
{

    /**
     * 加密方法，对数据进行加密，返回加密后的数据
     * @param string $data 要加密的数据
     * @return string
     */
    public function setEncrypt($data,$iv)
    {
        return openssl_encrypt($data, 'AES-256-CBC', env('APP_KEY'),0, $iv);
    }
    /**
     * 解密方法，对数据进行解密，返回解密后的数据
     * @param string $data 要解密的数据
     * @return string
     */
    public function getDecrypt($data,$iv)
    {
        return openssl_decrypt($data,'AES-256-CBC', env('APP_KEY'), 0, $iv);
    }
    //获取用户身份令牌
    public function token($user){
        //撤销用户所有令牌
       // $user->tokens()->delete();
        //重新发布令牌
        return $user->createToken('user_login:'.$user->id)->plainTextToken;
    }
    private function respondWithToken($user,$request)
    {
        return [
            'access_token' => $this->token($user),
            'token_type' => 'Bearer',
            'expires_in' => 1800,
            'refresh_in'=>1800,
            'user_info' => $user,
        ];
    }
    //更新用户
    public function userUpdate($userId,Array $array){

       User::query()->where('id',$userId)->update($array);
    }

    /* *
 * 获取星座
 * 星座是按阳历来计算的
 * $month 阳历月份
 * $day  阳历日期
 * */
    protected function get_xingzuo($month, $day)
    {
        $xingzuo = '';
        // 检查参数有效性
        if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
            return $xingzuo;
        }

        if (($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)) {
            $xingzuo = "水瓶座";
        } else if (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) {
            $xingzuo = "双鱼座";
        } else if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 19)) {
            $xingzuo = "白羊座";
        } else if (($month == 4 && $day >= 20) || ($month == 5 && $day <= 20)) {
            $xingzuo = "金牛座";
        } else if (($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)) {
            $xingzuo = "双子座";
        } else if (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) {
            $xingzuo = "巨蟹座";
        } else if (($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)) {
            $xingzuo = "狮子座";
        } else if (($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)) {
            $xingzuo = "处女座";
        } else if (($month == 9 && $day >= 23) || ($month == 10 && $day <= 23)) {
            $xingzuo = "天秤座";
        } else if (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) {
            $xingzuo = "天蝎座";
        } else if (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) {
            $xingzuo = "射手座";
        } else if (($month == 12 && $day >= 22) || ($month == 1 && $day <= 19)) {
            $xingzuo = "摩羯座";
        }

        return $xingzuo;
    }

    /**
     * 获取用户年龄
     * @param $birthday
     */
    protected function getAge($birthday){
        $old = date('Y-m-d H:i:s',$birthday);
        return now()->diffInYears($old);
    }
    //查询钱包金币数
    protected function getWallet($user){
        return UserWallet::query()->where('uid',$user->im_id)->first();
    }
    protected function incomeRecord($model,$array,$expend){
        $model->diamondincome()->save(new UserDiamondIncome($array));

        $model->coinincome()->save(new UserCoinIncome($expend));
    }
    protected function getCharmValue($user,$room_num,$diamond){
        $config = Cache::remember('get_charm_value', 7200, function () {
            return FamilyConfig::query()->pluck('value','key');
        });

        if($user->union_id>0){
            if($user->union_id==$room_num->union_id){//同一家族
                return round($diamond,2);
            }else{
                return round($diamond,2);
            }
        }else{//没有家族
            return round($diamond,2);
        }
    }
    //获取缓存房间
    protected function getCacheRoom($room_num){
        return Cache::remember('get_cache_room'.$room_num, 7200, function ()use($room_num) {
            return Live::query()->where('room_num',$room_num)->first();
        });
    }
    //获取缓存礼物
    protected function getCacheGift($request){
        return Cache::remember('get_cache_gift'.$request->gift_id, 7200, function ()use($request) {
            return Gift::query()->find($request->gift_id);
        });
    }

    /**
     * 缓存魅力值
     */
    protected function IncSitCharm($room,$sitId,$value){
        $key = 'charm-cache'.$room->room_num;
        $res = Redis::hexists($key,$sitId);
        if(!$res){
            $value = $room->seat_charm[$sitId]+$value;
        }
        Redis::hincrby($key,$sitId,$value);
    }

    /**
     * 获取魅力值数组
     * @param $room_num
     * @return mixed
     */
    protected function getSitCharm($room_num){
        $key = 'charm-cache'.$room_num;
        return Redis::hgetall($key);
    }

    /**
     * 删除房间所有魅力值
     * @param $room_num
     */
    protected function delSitAllCharm($room){
        $key = 'charm-cache'.$room->room_num;
        $arr = Redis::hkeys($key);
        foreach ($arr as $item){
            $this->delSingleCharm($room,$item);
        }
    }

    /**
     * 删除房间单个魅力值
     * @param $room_num
     * @param $item
     */
    protected function delSingleCharm($room,$item){
        $key = 'charm-cache'.$room->room_num;
        Redis::hdel($key,$item);
    }
    /**
     * 缓存里面设置当前房间的魅力值
     * @param $array
     * @param $room
     * @return mixed
     */
    public function setSitCharm($array,$room){
        $key = 'charm-cache'.$room->room_num;
        $data = Redis::hgetall($key);
        foreach ($data as $key=>$value){
            $array[$key]= $value;
        }
        return $array;
    }
    /**
     * 缓存倒计时
     */
    protected function userCacheCountdown($room,$sitId,$value){
        $key = 'charm-cache-contdown'.$room->room_num;
        $res = Redis::hexists($key,$sitId);
        if(!$res){
            Redis::hincrby($key,$sitId,$value);
        }
    }
    /**
     * 获取全麦位倒计时
     * @param $array
     * @param $room
     * @return mixed
     */
    public function getSitCountdown($array,$room){
        $key = 'charm-cache-contdown'.$room->room_num;
        $data = Redis::hgetall($key);
        foreach ($data as $k=>$value){
            $array[$k]= $value;
        }
        return $array;
    }
    /**
     * 删除当前倒计时
     * @param $room_num
     * @param $item
     */
    protected function delCountdown($room,$item){
        $key = 'charm-cache-contdown'.$room->room_num;
        Redis::hdel($key,$item);
    }
    protected function getCountdown($room,$field){
        $key = 'charm-cache-contdown'.$room->room_num;
        return Redis::hexists($key,$field);
    }

    /**
     * 获取房间数据
     */
    protected function getRoom($room_num){
        return Live::query()
            ->with(['bg','user'=>function($query){
                $query->select('id','nickname');
            }])
            ->where('room_num',$room_num)->first();
    }
    //获取当前房间实时排行榜
    protected function hotSearch($room_num){
        $day = now()->format("Ymd");
        $value = 'ability_value';
        return UserDayRoomList::query()
            ->with(['user'=>function($query){
                $query->select('im_id','avatar');
            }])
            ->where('room_num',$room_num)
            ->where($value,'<>',0)
            ->where('day',$day)->orderByDesc($value)
            ->limit(3)
            ->get()->toArray();
    }
    public function checkData($user,$contents,$type=1,$category=1){
        return [
          'uid'=>$user->id,
          'nickname'=>$user->nickname,
          'type'=>$type,
          'category'=>$category,
          'contents'=>$contents,
        ];
    }
    //房间数据
    public function checkRoomData($user,$room,$contents,$type=1,$category=1){
        return [
            'uid'=>$user->id,
            'room_num'=>$room->room_num,
            'nickname'=>$user->nickname,
            'type'=>$type,
            'category'=>$category,
            'contents'=>$contents,
        ];
    }

    /**
     * 过滤敏感词
     * @param $str
     * @return mixed
     */
    protected function filterWord($str){
       // $url = 'https://service-lluf5io3-1304843926.sh.apigw.tencentcs.com'.'/filter_word';

        $url = 'https://service-lluf5io3-1304843926-in.sh.apigw.tencentcs.com:9000'.'/filter_word';
        //$url = 'https://service-lluf5io3-1304843926.sh.apigw.tencentcs.com:443'.'/filter_word';
        $data = ['key1'=>$str];
        $response = Http::asForm()->post($url,$data);
        $result = $response->body();
        $array = json_decode($result,true);
        //info('获取数据'.$array['body']['result']);
        return $array['body']['result'];
    }
    //单个修改用户资料
    protected function changeUserProfile($user,$str,$key_word){
        $data = User::query()->where('id',$user->id)->first();
        $data->$str = $key_word;
        $data->save();
        return $data;
    }
}
